package com.zhuanzhuan.hero.user.service.impl;

import com.bj58.zhuanzhuan.zzentry.common.service.entity.ServiceHeaderEntity;
import com.zhuanzhuan.hero.user.converter.LabelConverter;
import com.zhuanzhuan.hero.user.dto.label.SaveUserBoundLevelLabelDTO;
import com.zhuanzhuan.hero.user.entity.HeroLabelInfo;
import com.zhuanzhuan.hero.user.entity.HeroUserInfo;
import com.zhuanzhuan.hero.user.entity.HeroUserLabelRelation;
import com.zhuanzhuan.hero.user.enums.ExceptionMsgEnum;
import com.zhuanzhuan.hero.user.enums.LabelTypeEnum;
import com.zhuanzhuan.hero.user.pojo.bo.LabelInfoQueryBO;
import com.zhuanzhuan.hero.user.service.*;
import com.zhuanzhuan.hero.user.util.Assert;
import com.zhuanzhuan.hero.user.vo.label.LevelLabelVO;
import com.zhuanzhuan.hero.user.vo.label.ManagementLabelVO;
import com.zhuanzhuan.hero.user.vo.label.UserBoundLevelLabelVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName UserLabelServiceImpl
 * @Description
 * @Author hanjunjun
 * @Date 2024/6/24 14:36
 */
@Service
@Slf4j
public class UserManagementLabelServiceImpl implements IUserManagementLabelService {

    @Autowired
    private HeroLabelInfoService labelInfoService;

    @Resource
    private HeroUserInfoService userInfoService;

    @Resource
    private HeroUserLabelRelationService userLabelRelationService;

    @Resource
    private IUserService userService;

    @Override
    public UserBoundLevelLabelVO queryUserBoundLevelLabel(Long uid, Integer labelType) {
        UserBoundLevelLabelVO vo = new UserBoundLevelLabelVO();

        //查询所有标签
        List<HeroLabelInfo> labelInfos = labelInfoService.listByParam(LabelInfoQueryBO.builder().labelType(labelType).build());
        if (CollectionUtils.isEmpty(labelInfos)) {
            log.info("查询标签为空 labelType={}", labelType);
            return vo;
        }

        //维护层级关系
        List<LevelLabelVO> levelLabelList = LabelConverter.buildLevelLabel(labelInfos);
        //vo转换
        List<ManagementLabelVO> managementLabels = levelLabelList.stream().map(levelLabel -> {
            ManagementLabelVO managementLabelVO = new ManagementLabelVO();
            BeanUtils.copyProperties(levelLabel, managementLabelVO);
            return managementLabelVO;
        }).collect(Collectors.toList());
        vo.setLabels(managementLabels);

        //用户已绑定的标签  归类到对应的一级标签下
        this.buildBoundBabels(uid, labelType, managementLabels);

        //个人简介
        vo.setPersonalDescription(this.queryPersonalIntroduction(uid));

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserBoundLevelLabel(Long uid, SaveUserBoundLevelLabelDTO saveBoundLabelDTO, ServiceHeaderEntity header) {
        Integer labelType = Integer.valueOf(saveBoundLabelDTO.getLabelType());

        //后期的个人简介可能不在这个接口保存   修改了个人简介也需要发mq给搜广推，一期发送mq的逻辑先放在userRelateLabels里
        if (LabelTypeEnum.MANAGEMENT.getCode().equals(labelType)) {
            userService.modifyPersonalIntroduction(uid, saveBoundLabelDTO.getPersonalDescription(), header);
        }

        List<Long> boundLabelIds = saveBoundLabelDTO.getLabels()
            .stream()
            .map(SaveUserBoundLevelLabelDTO.LabelInfo::getBoundLabels)
            .flatMap(Collection::stream)
            .map(SaveUserBoundLevelLabelDTO.BoundLabelDTO::getLabelId)
            .collect(Collectors.toList());
        userLabelRelationService.userRelateLabels(uid, labelType, boundLabelIds);

        //个人信息是否完善 完善则发送mq
        userService.personInfoPerfectionBroadcast(uid);
    }

    /**
     * 赋值【用户已绑定标签】字段
     *
     * @param uid
     * @param labelType
     * @param managementLabelList 最外层是一级标签   已包含了层级关系
     * @return void
     * @author  hanjunjun
     * @date 2024/6/24
     **/
    private void buildBoundBabels(Long uid, Integer labelType, List<ManagementLabelVO> managementLabelList) {
        //查询用户已绑定的标签    这里是三级标签
        List<HeroUserLabelRelation> userRealateLabels =
            userLabelRelationService.queryUserRealateLabels(uid, labelType);
        if (CollectionUtils.isEmpty(userRealateLabels)) {
            log.info("用户未绑定任何标签");
            return;
        }
        List<Long> boundLabelIds =
            userRealateLabels.stream().map(HeroUserLabelRelation::getLabelId).collect(Collectors.toList());

        //已绑定的三级标签
        managementLabelList.forEach(firstLevelLabel -> {
            List<LevelLabelVO> secondLabels = firstLevelLabel.getChildLabels();
            List<LevelLabelVO> allThirdLevelLabels = new ArrayList<>();
            secondLabels.forEach(secondLevelLabel -> {
                allThirdLevelLabels.addAll(secondLevelLabel.getChildLabels());
            });
            //三级标签中筛选出已绑定的
            List<LevelLabelVO> boundThirdLevelLabels = allThirdLevelLabels.stream()
                .filter(labelVo -> boundLabelIds.contains(labelVo.getLabelId()))
                .collect(Collectors.toList());
            firstLevelLabel.setBoundLabels(boundThirdLevelLabels);
        });
    }

    /**
     * 查询个人简介
     *
     * @param uid
     * @return java.lang.String
     * @author  hanjunjun
     * @date 2024/6/24
     **/
    private String queryPersonalIntroduction(Long uid) {
        HeroUserInfo heroUserInfo = userInfoService.getUserByUid(uid);
        Assert.notNull(heroUserInfo, ExceptionMsgEnum.BUSINESS_ERROR);

        return heroUserInfo.getPersonalIntroduction();
    }

}
